<?php
// 应用公共文件

use broadcast\redis\RedisService;
use think\facade\Cache;
use think\facade\Db;
use broadcast\utils\Curl as CurlModel;
use jianyan\excel\Excel;
use broadcast\redis\setRedis;
use think\facade\Config;
use app\models\system\SystemWebsite;

if (!function_exists('__url')) {

    /**
     * 构建URL地址
     * @param string $url
     * @param array $vars
     * @param bool $suffix
     * @param bool $domain
     * @return string
     */
    function __url(string $url = '', array $vars = [], $suffix = true, $domain = false)
    {
        return url($url, $vars, $suffix, $domain)->build();
    }
}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('xdebug')) {

    /**
     * debug调试
     * @param string|array $data 打印信息
     * @param string $type 类型
     * @param string $suffix 文件后缀名
     * @param bool $force
     * @param null $file
     */
    function xdebug($data, $type = 'xdebug', $suffix = null, $force = false, $file = null)
    {
        !is_dir(runtime_path() . 'xdebug/') && mkdir(runtime_path() . 'xdebug/');
        if (is_null($file)) {
            $file = is_null($suffix) ? runtime_path() . 'xdebug/' . date('Ymd') . '.txt' : runtime_path() . 'xdebug/' . date('Ymd') . "_{$suffix}" . '.txt';
        }
        file_put_contents($file, "[" . date('Y-m-d H:i:s') . "] " . "========================= {$type} ===========================" . PHP_EOL, FILE_APPEND);
        $str = (is_string($data) ? $data : (is_array($data) || is_object($data)) ? print_r($data, true) : var_export($data, true)) . PHP_EOL;
        $force ? file_put_contents($file, $str) : file_put_contents($file, $str, FILE_APPEND);
    }
}

if (!function_exists('sysconfig')) {

    /**
     * 获取系统配置信息
     * @param $group
     * @param null $name
     * @return array|mixed
     */
    function sysconfig($group, $name = null)
    {
        $where = ['group' => $group];
        $value = empty($name) ? Cache::get("sysconfig_{$group}") : Cache::get("sysconfig_{$group}_{$name}");

        if (empty($value)) {
            if (!empty($name)) {
                $where['name'] = $name;
                $value = \app\admin\model\SystemConfig::where($where)->value('value');
                Cache::tag('sysconfig')->set("sysconfig_{$group}_{$name}", $value, 3600);
            } else {
                $value = \app\admin\model\SystemConfig::where($where)->column('value', 'name');
                Cache::tag('sysconfig')->set("sysconfig_{$group}", $value, 3600);
            }
        }
        return $value;
    }
}

if (!function_exists('array_format_key')) {

    /**
     * 二位数组重新组合数据
     * @param $array
     * @param $key
     * @return array
     */
    function array_format_key($array, $key)
    {
        $newArray = [];
        foreach ($array as $vo) {
            $newArray[$vo[$key]] = $vo;
        }
        return $newArray;
    }

}

if (!function_exists('auth')) {

    /**
     * auth权限验证
     * @param $node
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function auth($node = null)
    {
        return true;
    }

}

//可选功能
if (!function_exists('websit_links')) {
    function websit_links()
    {
        return [
            'http://baidu.com'
        ];
    }
}

//主要颜色配色方案
if (!function_exists('allColor')) {
    function allColor()
    {
        $Main = [
            1 => ['backgroundbottom' => '#191919','noSelect'=>'#191919','search'=>'#191919','backgroundtop' => '#242424', 'main' => '#ff8533', 'menu' => '#ff8533', 'is_cover' => false, 'title' => '黑橙', "value" => 1],
            2 => ['backgroundbottom' => '#191919','noSelect'=>'#191919','search'=>'#191919','backgroundtop' => '#242424', 'main' => '#ff2828', 'menu' => '#FFFFFF', 'is_cover' => false, 'title' => '黑红', "value" => 2],
            3 => ['backgroundbottom' => '#191919','noSelect'=>'#191919','search'=>'#191919','backgroundtop' => '#242424', 'main' => '#ff8533', 'menu' => '#ff8533', 'is_cover' => true, 'title' => '自定义', "value" => 3],
            4 => ['backgroundbottom' => '#384379','noSelect'=>'#2A497C','search'=>'#1B3756','backgroundtop' => '#232c57', 'main' => '#598adc', 'menu' => '#FFB43F', 'is_cover' => false, 'title' => '蓝紫', "vlaue" => 4],
            5 => ['backgroundbottom' => '#F6F7F8','noSelect'=>'#EEF1F6','search'=>'#EEF1F6','backgroundtop' => '#ffffff', 'main' => '#1677ff', 'menu' => '#4A4F85', 'is_cover' => false, 'title' => '蓝白', "value" => 5],
        ];

        return $Main;

    }
}
//可调配功能
if (!function_exists('functionList')) {
    function functionList()
    {
        $data = array();

        $menus = [
            'teacher' => ['label' => '老师简介'],
            'curriculum' => ['label' => '课程安排'],
            'software' => ['label' => '软件下载'],
            'warehouse' => ['label' => '建仓提醒'],
            'position' => ['label' => '平仓提醒'],
            'individual' => ['label' => '个股诊断'],
            'economics' => ['label' => '财经日历'],
            'market' => ['label' => '市场评论'],
            'previous' => ['label' => '往期视频'],
            'lecturer' => ['label' => '讲师排行'],
            'service' => ['label' => '服务体系'],
            'download' => ['label' => '指标下载'],
            'courseware' => ['label' => '高级课件'],
            'dragon' => ['label' => '龙虎榜单'],

        ];

        $modular = [
            'rotation' => ['label' => '轮播图'],
            'gifts' => ['label' => '送礼物'],
            'online' => ['label' => '在线成员'],
            'lecturerranking' => ['label' => '讲师排行'],
            'marketing' => ['label' => '行情动态'],
            'notice' => ['label' => '公告'],
            'logo' => ['label' => 'logo'],
        ];

        $function = [
            'register' => ['label' => '注册'],
            'sign' => ['label' => '签到'],
            'luck' => ['label' => '抽奖'],
            'desktop' => ['label' => '保存到桌面'],
            'peeler' => ['label' => '换肤'],
            'mobile' => ['label' => '手机直播']
        ];

        $data = ['menus' => $menus, 'modular' => $modular, 'function' => $function];

        return $data;

    }
}

/**
 * 处理时间
 * @param string $time 单位/秒
 */
if (!function_exists('handleTime')) {
    function handleTime($time)
    {
        if ($time > (60 * 60 * 24)) return (int)((int)$time / (60 * 60 * 24)) . '天';
        else if ($time > (60 * 60)) return (int)((int)$time / (60 * 60)) . "小时";
        else if ($time > 60) return (int)((int)$time / 60) . "分钟";
        else return ((int)$time) . "秒";
    }
}

/**
 * 生成游客的唯一id
 * @param string $key
 */
if (!function_exists('create_unique')) {
    function create_unique($key)
    {
        $prefix = ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'tourist', 'visitor', 'excursionist', 'sightseer'];
        $data = $_SERVER['HTTP_USER_AGENT'] . $_SERVER['REMOTE_ADDR'] . time() . rand();
        return $prefix[rand(1, count($prefix) - 1)] . sha1($data);
    }
}

/**
 * 获取用户ip
 */
if (!function_exists("getIps")) {
    function getIps($way = false)
    {   
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        $nowip = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches [0] : '0:0:0:0';
        if ($way == false) $nowip = setRedis::prohibitiplist($nowip);
        return $nowip;
    }
}

/**
 * 获取ip归属地
 * @param string $ip 用户ip
 */
if (!function_exists("ascriptions")) {
    function ascriptions($ip)
    {

        $host = "https://api01.aliyun.venuscn.com";
        $path = "/ip";
        $method = "GET";
        $appcode = "b75b012b5724490cb8321d1f36310a86";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "ip=".$ip;
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        $json = curl_exec($curl);
        $data = json_decode($json,true);
        
        if ($data['ret'] == 200 ) {
            return $data['data']['country']. '-' .$data['data']['region'] . "-" . $data['data']['city'];
        } else {
            $url = "https://www.maitube.com/ip/?ip=" . $ip;
            $curl = new CurlModel($url);
            $address = $curl->get();
            $address = explode(" : ", $address)[1];
            $addressstring = explode(" ", $address)[0];
            return $addressstring;
        }

        

    }
}


/**加密函数
 * @param operation ENCODE  加密   DECODE 解密
 *
 */
if (!function_exists("lockcode")) {
    function lockcode($string, $operation = 'DECODE', $key = 'qiview', $expiry = 0)
    {
        // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙   
        $ckey_length = 4;

        // 密匙   
        $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);

        // 密匙a会参与加解密   
        $keya = md5(substr($key, 0, 16));
        // 密匙b会用来做数据完整性验证   
        $keyb = md5(substr($key, 16, 16));
        // 密匙c用于变化生成的密文   
        $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) :
            substr(md5(microtime()), -$ckey_length)) : '';
        // 参与运算的密匙   
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)， 
        //解密时会通过这个密匙验证数据完整性   
        // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确   
        $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
            sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = '';
        $box = range(0, 255);
        $rndkey = array();
        // 产生密匙簿   
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度   
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        // 核心加解密部分   
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            // 从密匙簿得出密匙进行异或，再转成字符   
            $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
        }
        if ($operation == 'DECODE') {
            // 验证数据有效性，请看未加密明文的格式   
            if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
                substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            } else {
                return '';
            }
        } else {
            // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因   
            // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码   
            return $keyc . str_replace('=', '', base64_encode($result));
        }
    }
}


//设置ip
if (!function_exists("setIp")) {
    function setIp($ip)
    {
        $newip = sprintf("%u", ip2long($ip));
        return $newip;
    }
}

//获取ip 
if (!function_exists("getIp")) {
    function getIp($ip)
    {
        return long2ip($ip);
    }
}


//处理html
if (!function_exists("tohtml")) {
    function tohtml($html)
    {
        return str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $html);
    }
}


//获取用户的id
if (!function_exists('getGuid')) {
    function getGuid()
    {
        $onlyid = '';
        try {
            //新时间截定义,基于世界未日2012-12-21的时间戳。
            $endtime = 1356019200;//2012-12-21时间戳
            $curtime = time();//当前时间戳
            $newtime = $curtime - $endtime;//新时间戳
            $rand = rand(0, 99);//两位随机
            $all = $rand . $newtime;
            $onlyid = base_convert($all, 10, 36);//把10进制转为36进制的唯一ID

        } catch (Exception $e) {
            $onlyid = mt_rand(0, 1000000);
        }
        return $onlyid;

    }
}


//个股诊断 -- 类型
if (!function_exists("stocksType")) {
    function stocksType()
    {
        $data = [
            1 => ['title' => '现价买入', 'value' => 1],
            2 => ['title' => '现价卖出', 'value' => 2],
            3 => ['title' => '到价买入', 'value' => 3],
            4 => ['title' => '到价卖出', 'value' => 4],
            5 => ['title' => '限价买入', 'value' => 5],
            6 => ['title' => '限价卖出', 'value' => 6]
        ];
        return $data;
    }
}

//获取类型名称
if (!function_exists("stocksTypeName")) {
    function stocksTypeName($type) 
    {
        $data = [
            1 => ['title' => '现价买入', 'value' => 1],
            2 => ['title' => '现价卖出', 'value' => 2],
            3 => ['title' => '到价买入', 'value' => 3],
            4 => ['title' => '到价卖出', 'value' => 4],
            5 => ['title' => '限价买入', 'value' => 5],
            6 => ['title' => '限价卖出', 'value' => 6]
        ];
        return $data[$type]['title'];
    }
}


//课程表 -- 类型
if (!function_exists('curriculumList')) {
    function curriculumList()
    {
        $data = [
            ['title' => '星期一', 'value' => 1],
            ['title' => '星期二', 'value' => 2],
            ['title' => '星期三', 'value' => 3],
            ['title' => '星期四', 'value' => 4],
            ['title' => '星期五', 'value' => 5],
            ['title' => '星期六', 'value' => 6],
            ['title' => '星期日', 'value' => 7]
        ];
        return $data;
    }
}
//市场评论 -- 类型
if (!function_exists("MarketReview")) {
    function MarketReview()
    {
        $data = [
            ['title' => '黄金', 'value' => 1],
            ['title' => '货币', 'value' => 2],
            ['title' => '原油', 'value' => 3],
            ['title' => '股票', 'value' => 4]
        ];
        return $data;
    }
}
if (!function_exists('createDatabase')) {
    function createDatabase($database)
    {
        try {
            Db::execute("CREATE DATABASE IF NOT EXISTS `live-{$database}` DEFAULT CHARACTER SET utf8");
        } catch (\Exception $e) {
            return false;
        }
        return true;
    }
}


//获取开始时间 和 结束时间   的时间戳
if (!function_exists("startStopTimes")) {
    function startStopTimes($type)
    {
        switch ($type) {
            case 'stoday':          //今天的开始时间
                return strtotime(date('Y-m-d') . ' 00:00:00');
                break;
            case 'etoday':          //今天的结束时间
                return strtotime(date('Y-m-d') . ' 23:59:59');
                break;
            case 'sweek':           //本周的开始时间
                $timestamp = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('Y'));
                return $timestamp;
                break;
            case 'eweek':           //本周的结束时间
                $timestamp = mktime(23, 59, 59, date('m'), date('d') - date('w') + 7, date('Y'));
                return $timestamp;
                break;
            case 'smonth':          //本月的开始时间
                $timestamp = mktime(0, 0, 0, date('m'), 1, date('Y'));
                return $timestamp;
                break;
            case 'emonth':          //本月的结束时间
                $timestamp = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
                return $timestamp;
                break;
        }
    }
}


//导入
if (!function_exists("importinfo")) {
    function importinfo($file)
    {
        $list = Excel::import($file->getRealPath());
        unset($list[0]);
        return $list;
    }
}

// 获取房间互通规则
if (!function_exists("getNowInterWork")) {
    function getNowInterWork($website, $roomid)
    {
        $roomGroup = [];
        $redis = new RedisService(config('cache')['stores']['redis']);
        $nowInterWork = $redis->get("{$website}:nowInterWork");
        if (!empty($nowInterWork)) {
            $nowInterWork = json_decode($nowInterWork, true);
            foreach ($nowInterWork as $item) {
                $temp = explode(',', $item['roomds']);
                if (in_array($roomid, $temp)) {
                    $roomGroup = array_merge($roomGroup, $temp);
                }
            }
        }
        return array_unique($roomGroup);
    }
}


//动态设置数据库
if (!function_exists('dynamicSetMysql')) {
    function dynamicSetMysql($website)
    {
        if (empty(session("website"))) {
            session("website",$website);
        }
        $database_config = config('database');
        if (isset($redis_config['connections'][session("website")])) return;
        $now_database = setRedis::getCache($website, 'mysql');
        if (empty($now_database)) {
            $websiteInfo = SystemWebsite::where("website_ident", $website)->find();
            $mysqlLsit['type'] = "mysql";
            $mysqlLsit['hostname'] = $websiteInfo['mysql_host'];
            $mysqlLsit['database'] = "live_" . $websiteInfo['website_ident'];
            $mysqlLsit['username'] = $websiteInfo['mysql_usename'];
            $mysqlLsit['password'] = $websiteInfo['mysql_pass'];
            $mysqlLsit['hostport'] = "3306";
            setRedis::setCache($website, 'mysql', $mysqlLsit, 0);

            $now_database = $mysqlLsit;
        }

        $now_database['type'] = "mysql";
        $now_database['params'] = [

        ];
        if (isset($now_database['hostname1'])) {
            unset($now_database['hostname1']);
        }
        $now_database['charset'] = 'utf8';
        $now_database['prefix'] = "chat_";
        $now_database['fields_strict'] = true;
        $now_database['break_reconnect'] = false;
        $now_database['trigger_sql'] = true;
        $now_database['fields_cache'] = false;
    
        $database_config['connections'][session("website")] = $now_database;
        Config::set($database_config, 'database');
    }
}


//获取单个网站的数据
if (!function_exists("singleWebsite")) {

    function singleWebsite($type)
    {
        $low_config = setRedis::getCache(session("website"), "info");
        if ($low_config) {
            $config = $low_config;
        } else {
            $config = SystemWebsite::where("website_ident", session("website"))->find();
            if ($config) {
                $config = $config->toArray();
                setRedis::setCache(session("website"), 'info', $config, 0);
            }
        }
        switch ($type) {
            case "title":
                return $config['website_title'];
                break;
            case "image":
                return isset($config['website_logo']) ? $config['website_logo'] : "";
                break;
            case 'icon':
                return isset($config['website_ico']) ? $config['website_ico'] : "";
                break;
        }
    }
}

/**
 * 设置redis 配置
 */
if (!function_exists("editRedisConfig")) {
    function editRedisConfig($data)
    {
        if (!is_array($data)) {
            $data = json_decode($data, true);
        }
        $redis_config = Config::get("cache");
        if (isset($redis_config['stores']['single'])) return;
        $redis = [
            'type' => "redis",              // 驱动方式
            'host' => $data['host'],        // 地址
            'port' => $data['port'],
            'password' => $data['password'],//密码
            'serialize' => []               // 序列化机制
        ];
        //获取缓存信息
        $redis_config['stores']['single'] = $redis;      //设置缓存设置
        
        $config = Config::set($redis_config, 'cache');  //保存缓存设置
    }
}


/**
 * PHP计算两个时间段是否有交集（边界重叠不算）
 * @param string $beginTime1 开始时间1
 * @param string $endTime1 结束时间1
 * @param string $beginTime2 开始时间2
 * @param string $endTime2 结束时间2
 * @return bool
 */
if (!function_exists("timeParagraphHandle")) {
    function timeParagraphHandle($beginTime1 = '', $endTime1 = '', $beginTime2 = '', $endTime2 = '')
    {
        $status = $beginTime2 - $beginTime1;
        if ($status > 0) {
            $status2 = $beginTime2 - $endTime1;
            if ($status2 >= 0) {
                return false;
            } else {
                return true;
            }
        } else {
            $status2 = $endTime2 - $beginTime1;
            if ($status2 > 0) {
                return true;
            } else {
                return false;
            }
        }
    }
}


/**
 * 奖品列表
 */
if (!function_exists("showPrizeList")) {
    function showPrizeList()
    {
        $data = [
            ['prize' => '10元现金奖励', 'id' => 1, 'weight' => 0.1, 'type' => 'gold'],
            ['prize' => '一等奖', 'id' => 2, 'weight' => 0.2, 'type' => 'advert'],
            ['prize' => '二等奖', 'id' => 3, 'weight' => 0.3, 'type' => 'advert'],
            ['prize' => '三等奖', 'id' => 4, 'weight' => 0.3, 'type' => 'advert'],
            ['prize' => '四等奖', 'id' => 5, 'weight' => 0.3, 'type' => 'advert'],
            ['prize' => '安慰奖', 'id' => 6, 'weight' => 99, 'type' => 'advert']
        ];
        return $data;
    }
}

/**
 * 获取IM 管理员所属系统分组
 */
if (!function_exists("getAdminsGroup")) {
    // 1：超级管理员 5：总管理员 6：房间管理员
    function getAdminsGroup()
    {
        return [1, 5, 6];
    }
}

// 分割账户
if (!function_exists("spliceNickStr")) {
    function spliceStr($str, $start, $end)
    {
        if ($end) {
            $p1 = mb_strpos($str, $start) + mb_strlen($start);
            $p2 = mb_strpos($str, $end) - $p1;
            return mb_substr($str, $p1, $p2);
        } else {
            $p1 = mb_strpos($str, $start) + mb_strlen($start);
            return mb_substr($str, $p1);
        }
    }
}

if (!function_exists("spliceNickStr")) {
    function changeTimeType($seconds)
    {
        if ($seconds > 3600) {
            $hours = intval($seconds / 3600);
            $minutes = $seconds % 3600;
            $time = $hours . ":" . gmstrftime('%M:%S', $minutes);
        } else {
            $time = gmstrftime('%H:%M:%S', $seconds);
        }
        return $time;
    }
}



/**
 * 加密
 */
if (!function_exists("reversibleEncryption")) {
    function reversibleEncryption($data, $key = '981023') 
    {
        $char = "";
        $str = "";
        $key    =    md5($key);
        $x        =    0;
        $len    =    strlen($data);
        $l        =    strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= $key{$x};
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            $str .= chr(ord($data{$i}) + (ord($char{$i})) % 256);
        }
        return base64_encode($str);
    }
}

/**
 * 解密
 */
if (!function_exists("reversibleDecrypt")) {
    function reversibleDecrypt($data, $key = "981023")
    {
        $char = "";
        $str = "";
        $key = md5($key);
        $x = 0;
        $data = base64_decode($data);
        $len = strlen($data);
        $l = strlen($key);
        for ($i = 0; $i < $len; $i++)
        {
            if ($x == $l)
            {
                $x = 0;
            }
            $char .= substr($key, $x, 1);
            $x++;
        }
        for ($i = 0; $i < $len; $i++)
        {
            if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))
            {
                $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));
            }
            else
            {
                $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));
            }
        }
        return $str;
    }
}

/**
 * 获取股票行情动态
 */
if (!function_exists("newsStockLists")) {
    function newsStockLists($content) {
        $quotationList = array();
        $default = ["https://hq.sinajs.cn/list=sh000001", "https://hq.sinajs.cn/list=sz399001", "https://hq.sinajs.cn/list=sz399006"];
        if ($content == "") {
            $industry = $default;
        }else{
            $industry = explode(",",$content);
        }

        $pattern = '#"(.*?)"#i';

        for ($i = 0; $i < count($industry); $i++) {
            $url = new CurlModel($industry[$i]);
            $res = $url->get();
            $res = mb_convert_encoding($res, 'utf-8', 'gbk');
            //处理数据
            preg_match_all($pattern, $res, $matches);
            $str = $matches[1][0];
            $info = substr($str, 0, strlen($str) - 1);
            $info = explode(",", $info);
            //数据处理
            $item = array();
            //名称
            $item['name'] = $info[0];
            //当前价格
            $item['now'] = sprintf("%.2f", $info[3]);
            $item['proportion'] = sprintf("%.2f", (($info[3] - $info[2]) / $info[2]) * 100) . '%';
            $quotationList[] = $item;
        }
        return $quotationList;
    }
}

/**
 * 获取数字货币行情动态
 */
if (!function_exists("currencyDigitalLists")) {
    function currencyDigitalLists($content) {
        $data = array();
        $url = "https://fxhapi.feixiaohao.com/public/v1/ticker?start=1&limit=3";    //(默认美元)
        $urls = new CurlModel($url); 
        $res = $urls->get();
        $json = json_decode($res,true);
        if (!empty($json)) {
            if ($content == "") {
                foreach ($json as $key => $value) {
                    $data[$key]['proportion'] = $value['volume_24h_usd']." $";
                    $data[$key]['now'] = $value['price_usd']." $";
                    $data[$key]['name'] = $value['symbol'];
                    if ($key > 1) {
                        
                        break;
                    }
                }
            }else{
                $currencys = explode(",",$content);
                foreach ($json as $key => $value) {
                    if (in_array($value['symbol'],$currencys)) {
                        $data[$key]['proportion'] = $value['volume_24h_usd']." $";
                        $data[$key]['now'] = $value['price_usd']." $";
                        $data[$key]['name'] = $value['symbol'];
                    }
                }

               
            }
            return $data;
        }else{
            $data = array();
        }
        return $data;
    }
}


// 2021  -- 抽奖
if (!function_exists("get_rand")) {
    function get_rand($proArr) { 
        $result = ''; 
     
        //概率数组的总概率精度 
        $proSum = array_sum($proArr); //计算数组中元素的和
     
        //概率数组循环 
        foreach ($proArr as $key => $proCur) { 
            $randNum = mt_rand(1, $proSum); 
            if ($randNum <= $proCur) { //如果这个随机数小于等于数组中的一个元素，则返回数组的下标
                $result = $key; 
                break; 
            } else { 
                $proSum -= $proCur; 
            } 
        } 
     
        unset ($proArr); 
     
        return $result; 
    }
}







